define(['app'], function (app) {
    app.config(function($provide){
        $provide.decorator('RouterExtendProvider', function ($delegate, $rootScope, $filter, $stateParams, config, MMWService, $calculater, $mdDialog, $css, $timeout, $templateRequest, $mdlMarquee) {
            $css.add('module/moduleMSG/program/MSG00/MSG00.css');
            $css.add('module/moduleMSG/program/MSG01/MSG01.css');

            var mialController,
                mailTool = {
                    icon:'mail',
                    name:'SideMenu.message_list',
                    dot:0,
                    class:[],
                    click:function(tool){
                        var index = tool.class.indexOf('is-select');
                        if(index == -1){
                            tool.class.push('is-select');
                            $rootScope.loadSideSubMenu(undefined, {mode:'mailbox'});
                        } else {
                            tool.class.splice(index, 1);
                            $rootScope.hideSideSubMenu();
                        }
                    }
                },
                mailResponseCallback = {
                    'ServicesSTD.Module_MSG.send_notification_process':function(data){
                        $delegate.synchronize_time = data.synchronize_time;
                        var _same_mails = $filter('filter')($delegate.mails, {MSGNo:data.MSGNo});
                        if(_same_mails.length == 0){
                            document.getElementById('mail-sound').play();
                            //確保不會收到重複的
                            mailTool.dot++;
                            $delegate.mails.unshift(data);
                            if(data.slight_state != 0){
                                if(data.slight_type_no && data.slight_type_no !='')
                                    $delegate.slight_details[data.slight_type_no] += 1;
                            }
                            if(data.urgency == 3)
                                showNotification(data);
                        }
                    },
                    'ServicesSTD.Module_MSG.update_notification_process':function(data){
                        //移除
                        for(var i =0;i<$delegate.mails.length;i++){
                            if(data.readed_notification.length > 0
                                || data.sealed_notification.length > 0
                                || data.delete_notification.length > 0 ){
                                //取除已讀訊息
                                var _temp = data.readed_notification.indexOf($delegate.mails[i].MSGNo);
                                if(_temp != -1){
                                    data.readed_notification.splice(_temp, 1);
                                    //$delegate.mails.splice(i, 1);
                                    if($delegate.mails[i].status == 'Y'){
                                        $delegate.mails[i].status = 'R';
                                        CountUnreadMail(-1);
                                    }
                                    //i--;
                                } else {
                                    //取出封存訊息
                                    _temp = data.sealed_notification.indexOf($delegate.mails[i].MSGNo);
                                    if(_temp != -1){
                                        if($delegate.mails[i].status == 'Y'){
                                            CountUnreadMail(-1);
                                        }
                                        data.sealed_notification.splice(_temp, 1);
                                        $delegate.mails.splice(i, 1);
                                        i--;
                                    } else {
                                        //取出刪除訊息
                                        _temp = data.delete_notification.indexOf($delegate.mails[i].MSGNo);
                                        if(_temp != -1){
                                            if($delegate.mails[i].status == 'Y'){
                                                CountUnreadMail(-1);
                                            }
                                            data.delete_notification.splice(_temp, 1);
                                            $delegate.mails.splice(i, 1);
                                            i--;
                                        }
                                    }
                                }
                            } else {
                                break;
                            }
                        }
                    },
                    'ServicesSTD.Module_MSG.update_slight_state_process':function(data){
                        //找出訊息並更新
                        for(var i =0;i<$delegate.mails.length;i++){
                            if($delegate.mails[i].MSGNo == data.MSGNo){
                                $delegate.mails[i].slight_state = data.slight_state;
                                $delegate.mails[i].slight_user_no = data.slight_user_no;
                                $delegate.mails[i].description = data.description;
                                if($delegate.mails[i].slight_state == 0){
                                    if($delegate.slight_details[data.slight_type_no] > 0)
                                        $delegate.slight_details[data.slight_type_no] -= 1;
                                }
                                break;
                            }
                        }
                    }
                };
            $delegate.NotificationHub;
            $delegate.isShowMessage = false;
            $delegate.mails = [];
            $delegate.init = function(){
                $delegate.MailStart();
            };
            $delegate.PageConfig = {
                now_page:1,
                page_count:250,
                total_page:0
            };
            $delegate.slight_details = {
                'SLEquipment':0,
                'SLQuality':0,
                'SLMaterial':0,
                'SLProd':0
            };
            $delegate.MailStart = function(callback, failback){
                notification_info_get({
                    user_no:config.cache.account,
                    is_page:true,
                    now_page:$delegate.PageConfig.now_page,
                    page_count:$delegate.PageConfig.page_count
                }, function(data){
                    $delegate.mails = data.notification_details;
                    if(mialController!=undefined)
                        mialController.mailList = $delegate.mails;

                    $delegate.PageConfig.total_page = data.total_page;
                    $delegate.PageConfig.now_page = data.now_page;
                    // 20190701 modify by Dustdusk for M#: 如果伺服器上新郵件數量大於目前新郵件數量則提示
                    var _unread_notification_count = data.unread_notification_count||0;
                    if(_unread_notification_count>mailTool.dot)
                        document.getElementById('mail-sound').play();

                    // 安燈統計初始化
                    for(var _slight_type in $delegate.slight_details){
                        $delegate.slight_details[_slight_type] = 0;
                    }
                    // 安燈統計
                    mailTool.dot = data.unread_notification_count||0;
                    for(var i = 0; i< $delegate.mails.length; i++){
                        if($delegate.mails[i].slight_state != 0){
                            for(var _slight_type in $delegate.slight_details){
                                if($delegate.mails[i].slight_type_no == _slight_type){
                                    $delegate.slight_details[_slight_type]++;
                                    break;
                                }
                            }
                        }
                    }

                    $delegate.tag_details = data.tag_details;
                    $delegate.receive_type_details = data.receive_type_details;
                    $delegate.synchronize_time = data.synchronize_time; // 最後收到訊息的時間
                    //啟動SignalR
                    if($delegate.NotificationHub == undefined){
                        $delegate.NotificationHub = MMWService.createHub('NotificationHub', {
                            name:config.server.name,
                            query_string: 'GroupName=' + config.cache.account,
                            port:config.server.port,
                            adapter:'Notification',
                            connected:function(){
                                $timeout(function(){
                                    var index = mailTool.class.indexOf('disconnected');
                                    if(index != -1)
                                        mailTool.class.splice(index, 1);
                                    if(typeof(callback) == 'function')
                                        callback();
                                });
                            },
                            disconnected:function(){
                                if($delegate.NotificationHub.connection_close != 'manual'){
                                    $timeout(function(){
                                        var index = mailTool.class.indexOf('disconnected');
                                        if(index == -1)
                                            mailTool.class.push('disconnected');
                                        Reconnect();
                                    });
                                }
                            },
                            listeners:{
                                'Alert':function(data){
    								$timeout(function(){
                                        //測試用
                                        mailTool.dot++;
                                        $delegate.mails.push(data);
    									showNotification(data);
                                    });
                                },
                                'Response':function(data){
                                    $timeout(function(){
                                        var _callback = mailResponseCallback[data.uri];
                                        if(typeof(_callback) == 'function')
                                            MMWService.ConnectSuccess(data, {success:_callback});
                                    });
                                }
                            }
                        });
                    } else if(typeof(callback) == 'function'){
                        // 20230517 modify by Alan for M#131992: invoke()前應先確認連線狀態，避免報錯:
                        // SignalR: Connection must be started before data can be sent. Call .start() before .send()
                        if($delegate.NotificationHub.connection.state === $.signalR.connectionState.connected) {
                            callback();
                        } else if($delegate.NotificationHub.connection.state === $.signalR.connectionState.disconnected) {
                            $delegate.NotificationHub.connect().done(function() {
                                callback();
                            });
                        } 
                    }
                }, failback);
            };
            $delegate.MailStop = function(callback){
                if($delegate.NotificationHub != undefined){
                    $delegate.NotificationHub.disconnect();
                    $delegate.NotificationHub = undefined;
                }
                if(typeof(callback) == 'function'){
                    callback();
                }
            };
            //非正常斷線則5秒重新連線

            $delegate.MailRefresh = function(callback){
                $delegate.MailStart(callback);
            };
            $delegate.showNotificationPanel = function(mode, item){
                if(mode == 'read' && item.status == 'Y'){
                    item.status = 'R';
                    CountUnreadMail(-1);
                    update_notification_process_rt({notification_details:[item], user_no:config.cache.account}, function(){
                        $rootScope.showSideSubMenu('mailbox write_mail');
                        mialController.dialog.open(mode, item);
                    });
                } else {
                    $rootScope.showSideSubMenu('mailbox write_mail');
                    mialController.dialog.open(mode, item);
                }
            };
            $delegate.hideNotificationPanel = function(){
                mialController.dialog.close();
            };

            //20190906 modify by Dustdusk for M#: Add SignalR Service Event
            $delegate.AddEventListener = function(scope, name, method){
                mailResponseCallback[name] = method;
                scope.$on("$destroy", function handleDestroy() {
                    delete mailResponseCallback[name];
                });
            };

            $delegate.groups = [];
            //20200224 modify by Dustdusk for M#: Add SignalR Change Group
            $delegate.AddToGroup = function(group_name){
                $delegate.NotificationHub.invoke('AddToGroup', group_name);
            };
            $delegate.ChangeGroup = function(group_name, new_group_name){
                $delegate.NotificationHub.invoke('ChangeGroup', group_name, new_group_name);
            };
            $delegate.RemoveFromGroup = function(group_name){
                $delegate.NotificationHub.invoke('RemoveFromGroup', group_name);
            };

            // 20190616 modify by Dustdusk for M#58748: 修正選單開啟問題
            var goToModule = $delegate.goToModule;
            $delegate.goToModule = function(menuItem, callback, failback){
                if($rootScope.sideSubMenuMode && $rootScope.sideSubMenuMode.indexOf('mailbox') == 0){
                    mialController.dialog.close();
                    mailTool.class.splice(mailTool.class.indexOf('is-select'), 1);
                    mialController.deselectAll();
                }

                //$rootScope.hideSideSubMenu();
                goToModule(menuItem, callback, failback);
            };

            (function init(){
                var mailInstance = {
                    genController:genController,
                    genTemplate:function(sideMenuTemp, sideExtendTemp, callback){
                        $templateRequest('module/moduleMSG/program/MSG00/MSG00.tmp.html').then(function(MSG00){
                            sideMenuTemp += MSG00;
                            $templateRequest('module/moduleMSG/program/MSG01/MSG01.tmp.html').then(function(MSG01){
                                sideExtendTemp += MSG01;
                                callback(sideMenuTemp, sideExtendTemp);
                            });
                        });
                    }
                };
                $delegate.sideTools.push(mailTool);
                $delegate.extendSideMenus.push(mailInstance);
            })();

            function getUrgencyColor(urgency){
                switch (urgency){
                    case 1:
                        return 'green';
                    case 2:
                        return 'yellow';
                    case 3:
                        return 'red';
                }
                return '';
            }

            // 顯示訊息
            function showNotification(data){
                try{
                    $mdlMarquee.show(data.sender_name+'：'+data.content, {delay:30});
                    if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
                        cordova.plugins.notification.local.schedule(data);
                        cordova.plugins.notification.local.on('click', data, this);
                     } else {
                        //產生HTML5的通知
                        Notification.requestPermission().then(function(permission){
                            var notification = new Notification(data.title, {
                                icon : 'image/mdpi-icon.png',
                                body : data.content
                            });
                            notification.onclick = function(){
                                $timeout(function(){
                                    $delegate.showNotificationPanel('read', data);
                                });
                            };
                        });
                    }
                }catch(error){
                    console.error(error);
                }
            }

            $delegate.showSlight = function(){
                return config.cache.sys_parameter['SlightModule'] == 1;
                //return true;
            };
            var _filterItem = {};
            $delegate.showMailList = function(slight_type_no){
                _filterItem.slight_type_no = slight_type_no;
                mailTool.click(mailTool);
            };

            //mailbox controller
            function genController(controller){
                /*** Mailbox***/
                controller.init = function(){
                    controller.condition = {type: '0', value: ''};
                    controller.PageConfig = {page : 0, page_count : 25};
                    //controller.selectItem = null; //目前選擇的信件
                    controller.filterItem = _filterItem;
                    controller.mailList = $delegate.mails;
                    //controller.refresh();
                    controller.slight_details = $delegate.slight_details;
                };
                controller.key_input = function(event){
                    if(event!=undefined && event.keyCode == 13){
                        controller.filterItem.content = controller.condition.value;
                    }
                };

                controller.search = function(){
                    controller.filterItem.content = controller.condition.value;
                };

                controller.search_clear = function(){
                    //controller.filterItem.content = controller.condition.value;
                };

                controller.refresh = function(){
                    $delegate.hideNotificationPanel();
                    $delegate.MailStart();
                };

                //關閉訊息列表
                controller.close = function(){
                    //$delegate.hideNotificationPanel();
                    $rootScope.hideSideSubMenu();
                };

                // 切換查詢條件
                controller.loadConditionType = function(){
                    var conditionList = [
                        {type : '0', label: $filter('translate')('mailbox.condition.type_0')},
                        {type : '1', label: $filter('translate')('mailbox.condition.type_1')},
                        {type : '2', label: $filter('translate')('mailbox.condition.type_2')},
                        {type : '3', label: $filter('translate')('mailbox.condition.type_3')}
                    ];

                    $rootScope.showSelect({
                        label : 'label',
                        code : 'type',
                        selectCode : controller.condition.type,
                        list : conditionList,
                        confirm : function(item, dialog){
                            dialog.hide();
                            controller.condition.type = item.type;
                            controller.condition.value = '';
                        }
                    });
                };

                //新增信件
                controller.writeMail = function(){
                    if(!config.cache.permissions || config.cache.permissions.indexOf('MSG01')!=-1){
                        $delegate.showNotificationPanel('write', {
                            //title:'mailbox.title.new_announcement',
                            send_date: window.moment().format('YYYY-MM-DD HH:mm:ss'),
                            urgency: 1,
                            tags:[],
                            annexs:[],
                            receiverTypes:ReceiverType(),
                            receiverTags:GetAllTags(),
                            slight_level:1,
                            slight_type_no:''
                        });
                    } else {
                        $rootScope.showAlert($filter('translate')('common.msg.without_permissions'));
                    }
                };
                //點擊信件
                controller.itemClick = function(item){
                    if(!controller.isSelecting()){
                        if(controller.selectItem == item){
                            $delegate.hideNotificationPanel(item);
                        } else {
                            $delegate.showNotificationPanel('read', item);
                        }
                    } else {
                        controller.itemSelect(item);
                    }
                };
                //勾選信件
                controller.itemSelect = function(item, event){
                    if(event!=undefined)
                        event.stopPropagation();
                    item.isSelected = !item.isSelected;
                    $delegate.hideNotificationPanel();
                };
                //是否勾選信件中
                controller.isSelecting = function(){
                    var is_selecting = false;
                    for(var i = 0; i < controller.mailList.length; i++){
                        if(controller.mailList[i].isSelected){
                            is_selecting = true;
                            break;
                        }
                    }
                    return is_selecting;
                };
                //勾選全部信件
                controller.selectAll = function(){
                    $delegate.hideNotificationPanel();
                    if(controller.mailList && controller.mailList.length > 0){
                        controller.mailList.forEach(function(item){
                            item.isSelected = true;
                        });
                    }
                };
                //取消勾選全部信件
                controller.deselectAll = function(){
                    if(controller.mailList && controller.mailList.length > 0){
                        controller.mailList.forEach(function(item){
                            item.isSelected = false;
                        });
                    }
                };
                // 刪除勾選郵件
                controller.deleteMail = function(){
                    var notification_details = [],
                        temp_details = [];
                    if(controller.mailList && controller.mailList.length > 0){
                        controller.mailList.forEach(function(item){
                            if(item.isSelected){
                                var _item = angular.merge({}, item);
                                _item.status = 'D';
                                notification_details.push(_item);
                            } else {
                                temp_details.push(item);
                            }
                        });
                        $rootScope.showConfirm($filter('translate')('MSG01.msg.is_delete', notification_details), function(confirmDialog){
                            confirmDialog.hide();
                            CountUnreadMail(0 - notification_details.length);
                            update_notification_process({delete_notification_details:notification_details, user_no:config.cache.account}, function(data){
                                controller.mailList = $delegate.mails =  temp_details;
                            });
                        });
                    }
                };
                // 封存勾選郵件
                controller.sealMail = function(){
                    var notification_details = [],
                        temp_details = [];
                    if(controller.mailList && controller.mailList.length > 0){
                        controller.mailList.forEach(function(item){
                            if(item.isSelected){
                                item.status = 'S';
                                notification_details.push(item);
                            } else {
                                temp_details.push(item);
                            }
                        });
                    }
                    update_notification_process({notification_details:notification_details, user_no:config.cache.account}, function(data){
                        controller.mailList = $delegate.mails =  temp_details;
                    });
                };

                //分頁
                controller.getPages = function(list, PageConfig, filterItem){
                    if(list){
                        var temp_list = list.filter(function(item, index, array){
                            var isOK = true,
                                keys = Object.keys(filterItem);
                            for(var i =0; i<keys.length;i++){
                                var key = keys[i];
                                if(isOK && filterItem[key] && filterItem[key]!=''){
                                    if(!item[key]){
                                        isOK = false;
                                        break;
                                    } else if(item[key].indexOf(filterItem[key]) == -1){
                                        isOK = false;
                                        break;
                                    }
                                }
                            }
                            return isOK;
                        });
                        if(PageConfig){
                            if(temp_list.length != 0){
                                PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count);

                                if(PageConfig.page >= PageConfig.total_page){
                                    PageConfig.page = 0;
                                }
                                //4/2*1
                                //PageConfig.total_page = ($delegate.PageConfig.page_count/PageConfig.page_count) * $delegate.PageConfig.total_page;
                                var index = PageConfig.page*PageConfig.page_count;
                                return temp_list.slice(index, index+PageConfig.page_count);
                            } else {
                                PageConfig.total_page = 1;
                                PageConfig.page = 0;
                            }
                        } else {
                            return temp_list;
                        }
                    } else {
                        return list;
                    }
                };
                // 停用
                controller.nextPage = function(PageConfig){
                    notification_info_get({
                        user_no:config.cache.account,
                        is_page:true,
                        now_page:$delegate.PageConfig.now_page+1,
                        page_count:$delegate.PageConfig.page_count
                    }, function(data){
                        $delegate.mails = data.notification_details;
                        if(mialController!=undefined)
                            mialController.mailList = $delegate.mails;

                        $delegate.PageConfig.total_page = data.total_page;
                        $delegate.PageConfig.now_page = data.now_page;
                        PageConfig.now_page = ($delegate.PageConfig.page_count/PageConfig.page_count) * $delegate.PageConfig.now_page;
                        mailTool.dot = data.unread_notification_count||0;
                        $delegate.tag_details = data.tag_details;
                        $delegate.receive_type_details = data.receive_type_details;
                        $delegate.synchronize_time = data.synchronize_time; // 最後收到訊息的時間
                    });
                }

                //日期時間格式轉換(當天顯示時間, 否則顯示日期)
                controller.dateFormat = function(date){
                    var diffDays = window.moment().diff(date, "days");
                    if(diffDays == 0){
                        return window.moment(date).format('HH:mm');
                    } else {
                        return window.moment(date).format('MM/DD');
                    }
                };
                //緊急程度燈號
                controller.getLight = function(urgency){
                    return getUrgencyColor(urgency);
                };
                controller.showSlight = function(){
                    return $delegate.showSlight();
                };
                controller = genNotificationPanelController(controller);
                //選擇安燈類型
                controller.selectSlightType = function(type_no){
                    if(controller.filterItem.slight_type_no != type_no){
                        controller.filterItem.slight_type_no = type_no;
                    } else {
                        controller.filterItem.slight_type_no = undefined;
                    }
                    if (controller.filterItem.slight_type_no != undefined) {
                        for (var _key in $delegate.slight_details) {
                            if (_key === controller.filterItem.slight_type_no) {
                                controller.mailItem.slight_type_no = _key;
                                controller.mailItem.slight_type_name = $filter('translate')('mailbox.slight_type.t_' + _key);
                                controller.dialog.tag_change(controller.mailItem.slight_type_no, controller.mailItem.slight_type_name);
                                break;
                            }
                        }
                    }
                    else {
                        controller.mailItem.slight_type_no = '';
                        controller.mailItem.slight_type_name = '';
                        controller.dialog.tag_change(controller.mailItem.slight_type_no, controller.mailItem.slight_type_name);
                    }
                }
                mialController = controller;

                $rootScope.hideSideSubMenu = function(){
                    mialController.deselectAll();
                    angular.element(document.getElementById('side-sub-menu')).addClass('menu-hide');
                    $rootScope.isShowSideSubMenu = false;
                    $rootScope.selectModule = {};
                    if($rootScope.sideSubMenuMode && $rootScope.sideSubMenuMode.indexOf('mailbox') == 0){
                        mialController.dialog.close();
                        mailTool.class.splice(mailTool.class.indexOf('is-select'), 1);
                    }
                    $rootScope.sideSubMenuMode = '';
                };
                return controller;
            }
            //訊息視窗(讀 / 寫)
            function genNotificationPanelController(controller){
                controller.dialog = {};
                controller.dialog.open = function(mode, mailItem){
                    $delegate.isShowMessage = true;
                    mialController.selectItem = mailItem;
                    mialController.dialog.mode = mode;
                    mialController.dialog.mailItem = mailItem;
                };
                controller.dialog.tag_change = function (slight_type_no, slight_type_name) {
                    controller.dialog.mailItem.slight_type_no = slight_type_no;
                    controller.dialog.mailItem.slight_type_name = slight_type_name;
                };
                controller.dialog.close = function(){
                    $delegate.isShowMessage = false;
                    mialController.selectItem = undefined;
                    mialController.dialog.mode = '';
                    $rootScope.sideSubMenuMode = 'mailbox';
                };
                controller.dialog.clickReceiver = function(){
                    receiver_info_get(function(data){
                        var _mode = 'check';
                        if(controller.dialog.mailItem.slight_type_no != '')
                            _mode = 'single-group-check';
                        $rootScope.showTreeList({
                            mode:_mode,
                            label:'category_name',
                            code:'category',
                            list : data,
                            subLabel:'user_name',
                            subCode:'user_no',
                            subItemList:'receivers',
                            confirm : function(itemList, dialog){
                                controller.dialog.mailItem.sender_name = '';
                                controller.dialog.mailItem.senders = [];
                                var contain = '';
                                if(controller.dialog.mailItem.slight_type_no != ''){
                                    var _temp = $filter('filter')(itemList, {isSelect:true});
                                    if(_temp && _temp.length > 1){
                                        $rootScope.showAlert($filter('translate')('mailbox.msg.slight_need_single_group'));
                                        return;
                                    } else {
                                        _temp.forEach(function(item){
                                            controller.dialog.mailItem.category_no = item.category_no;
                                            controller.dialog.mailItem.sender_name = item.category_name;
                                            item.receivers.forEach(function(subItem){
                                                controller.dialog.mailItem.senders.push({user_no:subItem.user_no});
                                            });
                                        });
                                    }
                                } else {
                                    itemList.forEach(function(item){
                                        item.receivers.forEach(function(subItem){
                                            if(subItem.isSelect){
                                                // 20190623 modify by Dustdusk for M#:
                                                if(contain.indexOf(subItem.user_no+';') == -1){
                                                    if(controller.dialog.mailItem.sender_name != '')
                                                        controller.dialog.mailItem.sender_name += ', ';

                                                    controller.dialog.mailItem.sender_name += subItem.user_name;
                                                    contain += subItem.user_no +';';
                                                    controller.dialog.mailItem.senders.push({user_no:subItem.user_no});
                                                }
                                            }
                                        });
                                    });
                                }

                                dialog.hide();
                            }
                        });
                    });
                };
                controller.dialog.addReceiverType = function(){
                    $rootScope.showCheckList({
                        label : 'pipe_name',
                        code : 'pipe_no',
                        order : '$index',
                        list : controller.dialog.mailItem.receiverTypes,
                        confirm : function(checkList, dialog){
                            var select_count = 0;
                            controller.dialog.mailItem.receiverTypes.forEach(function(type){
                                if(type.isSelect == true){
                                    select_count++;
                                }
                            });
                            if(select_count > 0){
                                dialog.hide();
                            } else {
                                $rootScope.showAlert($filter('translate')('mailbox.msg.receive_type_empty'));
                            }

                        }
                    });
                };
                controller.dialog.cancelType = function(type){
                    if(type.isSelect){
                        var select_count = 0;
                        controller.dialog.mailItem.receiverTypes.forEach(function(type){
                            if(type.isSelect == true){
                                select_count++;
                            }
                        });
                        if(select_count > 1){
                            type.isSelect = false;
                        } else {
                            $rootScope.showAlert($filter('translate')('mailbox.msg.receive_type_empty'));
                        }
                    }
                };
                controller.dialog.clickTarget = function(){
                    $rootScope.showTreeList({
                        list : GetPrograms(),
                        confirm : function(item, subItem, dialog){
                            controller.dialog.mailItem.LinkProgram = subItem.code;
                            controller.dialog.mailItem.LinkProgramName = subItem.label;
                            dialog.hide();
                        }
                    });
                };
                controller.dialog.clickUrgency = function(urgency){
                    controller.dialog.mailItem.urgency = urgency;
                };
                controller.dialog.addTags = function(){
                    $rootScope.showCheckList({
                        label : 'name',
                        code : 'no',
                        order : '$index',
                        list : controller.dialog.mailItem.receiverTags,
                        confirm : function(checkList, dialog){
                            dialog.hide();
                        }
                    });
                };
                controller.dialog.cancelTag = function(tag){
                    if(tag.isSelect){
                        var select_count = 0;
                        controller.dialog.mailItem.receiverTags.forEach(function(type){
                            if(type.isSelect == true){
                                select_count++;
                            }
                        });
                        if(select_count > 1){
                            tag.isSelect = false;
                        } else {
                            $rootScope.showAlert($filter('translate')('mailbox.msg.tag_empty'));
                        }
                    }
                };
                controller.dialog.addAnnex = function(){
                    var annex_types = [
                        {label:$filter('translate')('mailbox.annex_type_file'), type:'file'}
                    ];
                    //if(window.cordova){
                        annex_types.push({label:$filter('translate')('mailbox.annex_type_pic'), type:'pic'});
                        //annex_types.push({label:$filter('translate')('mailbox.annex_type_voice'), type:'voice'});
                    //}
                    $rootScope.showSelect({
                        label : 'label',
                        code : 'type',
                        selectCode : controller.condition.type,
                        list : annex_types,
                        confirm : function(item, dialog){
                            dialog.hide();
                            mialController.dialog.mailItem.annexs.push({name:'破損照片.png', path:''});
                        }
                    });
                };
                controller.dialog.removeAnnex = function($event, index){
                    mialController.dialog.mailItem.annexs.splice(index, 1);
                };
                // 開啟片語視窗
                controller.dialog.loadPhrase = function(){
                    phrase_info_get(config.cache.account, function(phraseList){
                        $mdDialog.dialog(
                            'module/moduleMSG/program/MSG01/phrase.tmp.html',
                            function(dialog){
                                dialog.phraseList = phraseList;
                                dialog.filterItem = {isfavorite:undefined, phrase:''};
                                //dialog.order = '!isfavorite';
                                dialog.beforeShown = function(){
                                    //$css.add('module/system/program/mailbox/phrase.css');
                                };
                                dialog.setFavorite = function(item){
                                    item.isModify = 'Y';
                                    if(item.isfavorite == 'Y'){
                                        item.isfavorite = 'N';
                                    } else {
                                        item.isfavorite = 'Y';
                                    }
                                };
                                dialog.changeFilter = function(){
                                    if(dialog.filterItem.isfavorite == 'Y'){
                                        dialog.filterItem.isfavorite = undefined;
                                    } else {
                                        dialog.filterItem.isfavorite = 'Y';
                                    }
                                };
                                dialog.itemClick = function(item){
                                    //dialog.confirm(function(){
                                        dialog.hide();
                                        controller.dialog.mailItem.content = item.phrase;
                                    //});
                                };
                                dialog.openDESC = function(item){
                                    var _temp = item.phrase.replace(/(?:\\[rn]|[\r\n]+)+/g,'<br/>');
                                    $mdDialog.alert(_temp);
                                };
                                dialog.back = function(){
                                    dialog.hide();
                                };
                                dialog.confirm = function(callback){
                                    var _modify_phrase_list = [];
                                    dialog.phraseList.forEach(function(phrase){
                                        if(phrase.isModify == 'Y'){
                                            _modify_phrase_list.push(phrase);
                                        }
                                    });
                                    if(_modify_phrase_list.length > 0){
                                        favorite_phrase_process({user_no:config.cache.account,modify_phrase_detail:_modify_phrase_list}, function(){
                                            $rootScope.showToast($filter('translate')('MSG01.msg.phrase_save_success'));
                                            if(typeof(callback) == 'function'){
                                                callback();
                                            } else {
                                                dialog.hide();
                                            }
                                        });
                                    } else {
                                        $rootScope.showToast($filter('translate')('MSG01.msg.phrase_save_success'));
                                        if(typeof(callback) == 'function'){
                                            callback();
                                        } else {
                                            dialog.hide();
                                        }
                                    }
                                };
                                return dialog;
                            }
                        );
                    });
                };
                //M#78798 安燈訊息釋放/接收
                controller.dialog.receive_and_freed = function () {
                    var content = {};
                    content.msg_no = mialController.dialog.mailItem.MSGNo;
                    andon_receive_and_freed_process(content, function (data) {
                        controller.refresh();
                        if (data.send_status) {
                            if (data.send_status == 1) {
                                $rootScope.showToast($filter('translate')('MSG01.msg.has_receive_success'));
                            }
                            else {
                                $rootScope.showToast($filter('translate')('MSG01.msg.has_freed__success'));
                            }
                        }
                    })
                };
                // 送出訊息
                controller.dialog.send = function(){
                    var content = mialController.dialog.mailItem;
                    send_notification_process(content, function(){
                        $rootScope.showToast($filter('translate')('MSG01.msg.success'));
                        controller.dialog.close();
                    });
                };
                // 送出訊息
                controller.dialog.redirect = function(){
                    if(config.cache.device == 'phone')
                        FindMobileProgram(controller.dialog.mailItem.LinkProgram, JSON.parse(controller.dialog.mailItem.LinkParameter));
                    else
                        FindProgram(controller.dialog.mailItem.LinkProgram, JSON.parse(controller.dialog.mailItem.LinkParameter));
                };
                controller.dialog.showSlight = function(){
                    return $delegate.showSlight();
                };
                controller.dialog.changeSlightType = function(){
                    var _slight_types = [];
                    for(var _key in $delegate.slight_details){
                        _slight_types.push({name:$filter('translate')('mailbox.slight_type.t_'+_key), code:_key})
                    }
                    $rootScope.showSelect({
                        label : 'name',
                        code : 'code',
                        selectCode : controller.dialog.mailItem.slight_type_no,
                        list : _slight_types,
                        confirm : function(selectItem, radio_dialog){
                            radio_dialog.hide();
                            controller.dialog.mailItem.slight_type_no = selectItem.code;
                            controller.dialog.mailItem.slight_type_name = selectItem.name;

                            controller.dialog.mailItem.category_no = '';
                            controller.dialog.mailItem.sender_name = '';
                            controller.dialog.mailItem.senders = [];
                        },
                        cancel : function(){
                            controller.dialog.mailItem.slight_type_no = '';
                            controller.dialog.mailItem.slight_type_name = '';

                            controller.dialog.mailItem.category_no = '';
                            controller.dialog.mailItem.sender_name = '';
                            controller.dialog.mailItem.senders = [];
                        }
                    });
                };
                controller.dialog.changeSlightLevel = function(){
                    if(mialController.dialog.mode == 'write'){
                        if(mialController.dialog.mailItem.slight_level == 2){
                            mialController.dialog.mailItem.slight_level = 1;
                        } else {
                            mialController.dialog.mailItem.slight_level = 2;
                        }
                    }
                };
                controller.dialog.reply = function(){
                    $mdDialog.serviceDialog('MSG02Service',{
                        data:{
                            MSGNo:mialController.dialog.mailItem.MSGNo,
                            slight_type_no:mialController.dialog.mailItem.slight_type_no,
                            slight_level:mialController.dialog.mailItem.slight_level,
                            slight_state:mialController.dialog.mailItem.slight_state,
                            slight_user_no:config.cache.account
                        }
                    }, function(data){
                        mialController.dialog.mailItem.slight_state = data.slight_state;
                        controller.dialog.close();
                    });
                };
                controller.dialog.autoTitle = function () { // 標題自動生成

                    if (!controller.dialog.mailItem.slight_type_name || !controller.dialog.mailItem.urgency || !controller.dialog.mailItem.send_date) {
                        // 安燈類型、緊急程度、日期，其中一項不能為空，請重新確認
                        return $rootScope.showAlert($filter('translate')('mailbox.msg.column01'));
                    }

                    // 安燈類型, 緊急程度, 日期
                    var msg = controller.dialog.mailItem.slight_type_name + ', ' +
                        $filter('translate')('mailbox.urgency_' + controller.dialog.mailItem.urgency) + ', ' +
                        controller.dialog.mailItem.send_date;

                    controller.dialog.mailItem.title = msg;
                };
                controller.dialog.release_action = function () {

                };
                return controller;
            }

            // *****************************************************************
            function GetPrograms(){
                var programs = [];
                config.menu.forEach(function(menuItem){
                    if(menuItem.childs && menuItem.childs.length>0){
                        var module = {label:$filter('translate')(menuItem.title).replace('<br>', ''), code: menuItem.name, subItemList:[]};
                        menuItem.childs.forEach(function(childItem){
                            if(!childItem.panel && childItem.childs && childItem.childs.length>0){
                                childItem.childs.forEach(function(subChildItem){
                                    module.subItemList.push({label:$filter('translate')(subChildItem.title).replace('<br>', ''), code:subChildItem.name});
                                });
                            } else if(childItem.panel == true){
                                module.subItemList.push({label:$filter('translate')(childItem.title).replace('<br>', ''), code:childItem.default});
                            } else {
                                module.subItemList.push({label:$filter('translate')(childItem.title).replace('<br>', ''), code:childItem.name});
                            }
                        });
                        programs.push(module);
                    }
                });
                //console.log(programs);
                return programs;
            }

            function FindProgram(name, parameters){
                var target, prepareProgram = function(menuItem, subMenuItem){
                    var _temp = angular.extend({}, menuItem);
                    if(subMenuItem != undefined){
                        _temp.default = subMenuItem.name;
                        _temp.default_name = $filter('translate')(subMenuItem.title).replace('<br>', '');
                    } else {
                        _temp.default = menuItem.name;
                        _temp.default_name = $filter('translate')(menuItem.title).replace('<br>', '');
                    }
                    _temp.data = parameters;
                    return _temp;
                };

                for(var i = 0; i < config.menu.length; i++){
                    var menuItem = config.menu[i];
                    if(menuItem.name == name){
                        target = angular.extend({}, menuItem);
                        target.default_name = $filter('translate')(target.title).replace('<br>', '');
                        $rootScope.showConfirm($filter('translate')('mailbox.msg.is_redirect', target), function(dialog){
                            dialog.hide();
                            $rootScope.hideSideSubMenu();
                            $delegate.goToModule(target);
                        });
                        break;
                    } else {
                        for(var j = 0; j < menuItem.childs.length; j++){
                            var childItem = menuItem.childs[j];
                            if(childItem.panel == true && childItem.default == name){
                                target = angular.extend({}, childItem);
                                target.default_name = $filter('translate')(target.title).replace('<br>', '');
                            } else if(childItem.name == name){
                                target = prepareProgram(childItem);
                                break;
                            } else if(childItem.childs){
                                for(var k = 0; k < childItem.childs.length; k++){
                                    var subChildItem = childItem.childs[k];
                                    if(subChildItem.name == name){
                                        target = prepareProgram(childItem, subChildItem);
                                        break;
                                    }
                                }
                                if(target)
                                    break;
                            }
                        }
                        if(target){
                            $rootScope.showConfirm($filter('translate')('mailbox.msg.is_redirect', target), function(dialog){
                                dialog.hide();
                                $rootScope.hideSideSubMenu();
                                $delegate.goToProgram(target);
                            });
                            break;
                        }
                    }
                }
                if(target == undefined)
                    $rootScope.showAlert($filter('translate')('mailbox.msg.not_find_program', {program_name:name}));
            }

            function FindMobileProgram(name, parameters){
                var target,
                    findChild = function(menuItem, name){
                        var target;
                        for(var i = 0; i < menuItem.child.length; i++){
                            if(menuItem.child[i].child){
                                target = findChild(menuItem.child[i], name)
                            } else if(menuItem.child[i].permission == name){
                                target = menuItem.child[i];
                            }
                            if(target)
                                break;
                        }
                        return target;
                    };
                for(var i = 0; i < config.menu.length; i++){
                    if(config.menu[i].child){
                        target = findChild(config.menu[i], name);
                    } else if(menuItem.child[i].permission == name){
                        target = menuItem.child[i];
                    }
                    if(target)
                        break;
                }
                if(target){
                    var _target = angular.extend({}, target);
                    _target.data = parameters;
                    if(_target.data.data)
                        _target.data.data.parent = 'menu';
                    else
                        _target.data.data = {parent: 'menu'};
                    _target.default = target.name;
                    _target.default_name = $filter('translate')(_target.title).replace('<br>', '');
                    $rootScope.showConfirm($filter('translate')('mailbox.msg.is_redirect', _target), function(dialog){
                        dialog.hide();
                        $rootScope.hideSideSubMenu();
                        $delegate.goToProgram(_target);
                    });
                } else {
                    $rootScope.showAlert($filter('translate')('mailbox.msg.not_find_program', {program_name:name}));
                }
            }

            function ReceiverType(){
                var _temps = [];
                $delegate.receive_type_details.forEach(function(receive_type, i){
                    var temp = angular.merge({}, receive_type);
                    if(temp.pipe_no == 'Sys')
                        temp.isSelect = true;
                    else
                        temp.isSelect = false;
                    _temps.push(temp);
                });
                return _temps;
            }

            function GetAllTags(){
                var _temps = [];
                $delegate.tag_details.forEach(function(receive_type, i){
                    var temp = angular.merge({}, receive_type);
                    temp.isSelect = false;
                    _temps.push(temp);
                });
                return _temps;
            }

            function CountUnreadMail(count){
                if(count < 0 && mailTool.dot>0)
                    mailTool.dot += count
                else if(count < 0)
                    mailTool.dot += count;
            }

            function Reconnect(){
                $timeout(function(){
                    //重新取得新的郵件
                    $delegate.MailStart(function(){
                        // 無法成功取得一樣重新連線
                        $delegate.NotificationHub.connect();
                    }, Reconnect);
                }, 5*1000);
            }

            // *****************************************************************
            // 取得所有信件
            function notification_info_get(content, success, failback){
                MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_MSG.notification_info_get',
                    content : content,
                    success : function(data){
                        success(data);
                    },
                    error : failback,
                    netError : failback
                }, failback==undefined);
            }

            // 取得所有收件者
            function receiver_info_get(callback){
                MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_MSG.receiver_info_get',
                    content : {},
                    success : function(data){
                        callback(data);
                    }
                });
            }

            // 取得片語
            function phrase_info_get(user_no, callback){
                MMWService.pageNumberInfoGet({
                    page_mode: 'phrase_info_get',
                    query_condition_info:[
                        {column_name:'TBLMSGUserPhrase.MSGUserNo', query_mode:'0', value: user_no, merge_condition_model : 'AND'}
                    ]
                }, callback);
            }

            // 設定我的最愛片語
            function favorite_phrase_process(content, callback){
                MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_MSG.favorite_phrase_process',
                    content : content,
                    success : function(data){
                        callback(data);
                    }
                });
            }

            // 更新訊息(使用real_time呼叫)
            function update_notification_process(content, callback){
                MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_MSG.update_notification_process',
                    content : content,
                    success : function(data){
                        callback(data);
                    }
                });
            }

            // 更新訊息(使用real_time呼叫)
            function update_notification_process_rt(content, callback){
                var sendData = {
                    uri : 'ServicesSTD.Module_MSG.update_notification_process',
                    content : content
                };
                $delegate.NotificationHub.invoke('InvokeJSON', {
                    header:MMWService.prepareHeader(sendData),
                    content:MMWService.prepareContent(sendData)
                });
                if(typeof(callback) == 'function'){
                    callback();
                }
            }

            // 發送訊息
            function send_notification_process(content, callback){
                MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_MSG.send_notification_process',
                    content : content,
                    success : function(data){
                        callback(data);
                    }
                });
            }

            //M#78798 安燈釋放/接收
            function andon_receive_and_freed_process(content, callback) {
                MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_MSG.andon_receive_and_freed_process',
                    content: content,
                    success: function (data) {
                        callback(data);
                    }
                });
            }
            return $delegate;
        });
    });
});
